package com.xiaochen.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaochen.common.exception.XiaoChenException;
import com.xiaochen.manager.mapper.SysRoleUserMapper;
import com.xiaochen.manager.mapper.SysUserMapper;
import com.xiaochen.manager.service.SysUserService;
import com.xiaochen.model.dto.system.AssginRoleDto;
import com.xiaochen.model.dto.system.LoginDto;
import com.xiaochen.model.dto.system.SysUserDto;
import com.xiaochen.model.entity.base.UserLoginInfo;
import com.xiaochen.model.entity.system.SysUser;
import com.xiaochen.model.vo.common.ResultCodeEnum;
import com.xiaochen.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    /**
     * 用户登录
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        // 获取输入的验证码和存储到redis中的key
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        // 根据redis里面的key获取value
        String redisCode = redisTemplate.opsForValue().get(UserLoginInfo.USER_VALIDATE_CODE+key);
        System.out.println("captcha/////"+captcha);
        System.out.println("key///"+key);
        System.out.println("redisCode////"+redisCode);
        // 比较输入的验证码和存储到redis的验证码是否一致
        // 验证码不一致直接提示错误,
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)){
            throw new XiaoChenException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 验证码一致,删除redis里面的验证码然后继续下面的登录流程
        redisTemplate.delete(UserLoginInfo.USER_VALIDATE_CODE+key);

        // 1.获取用户名
        String userName = loginDto.getUserName();
        // 添加日志输出用户名
        System.out.println("用户名："+userName);
        // 2.查询数据库，获取用户信息
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);

        // 3.判断用户是否存在
        // 3.1不存在，返回错误信息
        if (sysUser == null){
            /*throw new RuntimeException("用户名不存在");*/
            throw new XiaoChenException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 3.2存在，判断密码是否正确
        // 3.2.1获取数据库中的密码
        String databasePassword = sysUser.getPassword();
        String inputPassword = loginDto.getPassword();
        // 3.2.2密码加密之后再比较,这里使用MD5加密
        inputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());

        // 3.3不正确，返回错误信息,登录不成功
        if (!databasePassword.equals(inputPassword)){
            /*throw new RuntimeException("密码不正确");*/
            throw new XiaoChenException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 3.4正确，返回用户信息,登录成功
        // 4.给用户设置token,存储在redis和session中
        // redis是以键值对存储的<K,V>--------------<token,用户信息>
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().set("user:login"+token,
                                        JSON.toJSONString(sysUser),
                                        12,
                                        TimeUnit.HOURS );
        // 5.返回
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 从redis中获取用户信息
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login"+token);
        SysUser sysUser = JSON.parseObject(userJson,SysUser.class);
        return sysUser;
    }

    /**
     * 退出登录
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login"+token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.selectByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void addSysUser(SysUser sysUser) {
        // 1.根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(sysUser.getUserName()) ;
        if(dbSysUser != null) {
            throw new XiaoChenException(ResultCodeEnum.USER_NAME_IS_EXISTS) ;
        }

        // 2.对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(1);
        sysUserMapper.addSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUserMapper.updateSysUser(sysUser);
    }

    /**
     * 删除用户
     */
    @Override
    public void deleteById(Integer userId) {
        sysUserMapper.deleteById(userId);
    }

    /**
     * 根据id查询用户
     */
    @Override
    public List<SysUser> selectById(Integer userId) {
        return sysUserMapper.selectById(userId);
    }

    /**
     * 分配角色
     */
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 1.根据userId删除之前分配的角色数据
        sysRoleUserMapper.deleteRoleByUserId(assginRoleDto.getUserId());
        // 2.重新分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        if(roleIdList != null && roleIdList.size() > 0){
            for (long roleId : roleIdList){
                sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
            }
        }
    }
}
